package com.fancy.listen;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SendEmail {

    @Autowired
    JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    public String sendMail;
    @Autowired
    RedisTemplate redisTemplate;

    @RabbitListener(queues = "fancy-music-email")
    public void sendMail (Map map) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sendMail);
        Object email = map.get("email");
        simpleMailMessage.setTo(email.toString());
        simpleMailMessage.setSubject("注册的验证码");
        int r = (int) ((Math.random()*8998)+1000+1);
        simpleMailMessage.setText("验证码：" + r);
        try {
            javaMailSender.send(simpleMailMessage);
            System.out.println(redisTemplate);
            redisTemplate.opsForValue().set(email.toString(),""+r);
            redisTemplate.expire(email,60*5, TimeUnit.SECONDS);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
